package artid.com.arttogoa.util;

/*******************************************************************************
 * Copyright (c) 2014 by ehoo Corporation all right reserved.
 * 2014-5-31 
 * 
 *******************************************************************************/

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * <pre>
 * 功能说明: 
 * 日期:	2014-5-31
 * 开发者:	熊彬
 * 
 * 历史记录
 *    修改内容：
 *    修改人员：
 *    修改日期： 2014-5-31
 * </pre>
 */
public class NetUtils {
	public static final String DM_WIDTH = "width";
	public static final String DM_HEIGHT = "height";
	public static final String DM_DENSITY = "density";
	public static final String DM_DPI = "densityDpi";

	/**
	 * 检查网络是否可用
	 * 
	 * @param mainActivity
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
		// TODO Auto-generated method stub
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 检查网络是否可用（真正检测网络是否可用，这里用百度网站来检测）
	 * @return
	 */
	public static final boolean isNetworkConnected() { 

		String result = null; 
		try { 
			String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网 
			Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次 
			// 读取ping的内容，可以不加 
			InputStream input = p.getInputStream(); 
			BufferedReader in = new BufferedReader(new InputStreamReader(input)); 
			StringBuffer stringBuffer = new StringBuffer(); 
			String content = ""; 
			while ((content = in.readLine()) != null) { 
				stringBuffer.append(content); 
			} 
			Log.d("------ping-----", "result content : " + stringBuffer.toString()); 
			// ping的状态 
			int status = p.waitFor(); 
			if (status == 0) { 
				result = "success"; 
				return true; 
			} else { 
				result = "failed"; 
			} 
		} catch (IOException e) { 
			result = "IOException"; 
		} catch (InterruptedException e) { 
			result = "InterruptedException"; 
		} finally { 
			Log.d("----result---", "result = " + result); 
		} 
		return false;
	}


	/**
	 * TODO 获取屏幕宽，高，分辨率，密度
	 * 
	 * @param act
	 * @return
	 */
	public static Map<String, String> getDisplayMetrics(Activity act) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			DisplayMetrics metric = new DisplayMetrics();
			act.getWindowManager().getDefaultDisplay().getMetrics(metric);
			int width = metric.widthPixels; // 屏幕宽度（像素）
			int height = metric.heightPixels; // 屏幕高度（像素）
			float density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
			int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240）
			map.put(DM_WIDTH, String.valueOf(width));
			map.put(DM_HEIGHT, String.valueOf(height));
			map.put(DM_DENSITY, String.valueOf(density));
			map.put(DM_DPI, String.valueOf(densityDpi));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}

	/**
	 * TODO 输入流转byte数组
	 * 
	 * @param is
	 * @return
	 */
	public static String readString(InputStream is) {
		return new String(readBytes(is));
	}

	public static byte[] readBytes(InputStream is) {
		try {
			byte[] buffer = new byte[1024];
			int len = -1;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * TODO Unicode编码转码
	 * 
	 * @param theString
	 * @return
	 */
	public static String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed   \\uxxxx   encoding.");
						}

					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';
					else if (aChar == 'n')
						aChar = '\n';
					else if (aChar == 'f')
						aChar = '\f';
					outBuffer.append(aChar);
				}
			} else
				outBuffer.append(aChar);
		}
		return outBuffer.toString();
	}

	/**
	 * dp转px
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * px转dp
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	

	public static String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}
		return sdDir.toString();
	}

	public static String getSSID(Activity act) {
		WifiManager wifiMan = (WifiManager) act
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifiMan.getConnectionInfo();
		// String mac = info.getMacAddress();// 获得本机的MAC地址
		String ssid = info.getSSID();// 获得本机所链接的WIFI名称
		return ssid; 
	}

	/**
	 * 打开当前应用权限设置
	 * @param context
	 */
	public static void getAppDetailSettingIntent(Context context) {
		Intent localIntent = new Intent();
		localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (Build.VERSION.SDK_INT >= 9) {
			localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
			localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
		} else if (Build.VERSION.SDK_INT <= 8) {
			localIntent.setAction(Intent.ACTION_VIEW);
			localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
			localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
		}
		context.startActivity(localIntent);
	}

}
